/**
 * 文件随机读写 https://www.bilibili.com/video/BV1vs411n7TH?p=124
 */
#include "../Utils/FileIOUtils.h"

static char *FILE_READ_PATH = "../Read_Write_Test/test.txt";
static char *FILE_RAND_WRITE_PATH = "../Read_Write_Test/9.文件随机-写.txt";

void random_read();
void copy();
void random_write();

int main() {
    //1.随机读
//    random_read();
    //2.先拷贝一份, 从拷贝文件里随机写
    copy();
    //3.随机写
    random_write();
    return EXIT_SUCCESS;
}

//1.随机读
void random_read() {
    FILE *read = file_open_r(FILE_READ_PATH);
    char arr[100];
    //1.读取字符串
    char *str0 = file_gets(arr, 100, read);
    printf("1.读取1行字符串: \"%s\"\n", arr);       //"//remarks 是非得失\r\n"

    //2.光标偏移回去8位
    int fail0 = file_seek(read, -8, SEEK_CUR);
    if (fail0) return;
    /**
     * 再次读取
     * ∵3个汉字(占6位) + \r\n(占2位) = 8位
     * ∴回滚后再次读取: 非得失
     */
    char *str1 = file_gets(arr, 100, read);
    printf("2.光标从SEEK_CUR(当前位置)偏移 %d 位, 再次读取1行: \"%s\"\n", -8, arr);//"非得失\r\n"

    //3.从起始位置开始偏移
    int fail1 = file_seek(read, 6, SEEK_SET);
    char *str2 = file_gets(arr, 100, read);
    printf("3.光标从SEEK_SET(起始位置)偏移 %d 位, 再次读取1行: \"%s\"\n", 6, arr);//"rks 是非得失\r\n"

    //4.从文件末尾开始偏移
    int fail2 = file_seek(read, -173, SEEK_END);
    char *str3 = file_gets(arr, 100, read);
    printf("4.光标从SEEK_END(文件末尾)偏移 %d 位, 再次读取1行: \"%s\"\n", -173, arr);//"for (int n = 0; n < 2; n++) {\r\n"

    file_close(read);
}

//2.先拷贝一份, 从拷贝文件里随机写
void copy() {
    int fail0 = file_copy(FILE_READ_PATH, FILE_RAND_WRITE_PATH, 1);
    if (fail0) {
        printf("拷贝失败, fail = %d\n", fail0);
        return;
    } else {
        printf("拷贝成功!\n");
    }
}

//3.随机写
void random_write() {
    //可读写方式打开文件
    FILE *write = file_open_r_plus(FILE_RAND_WRITE_PATH);
    long pos0 = file_tell(write);
    printf("光标当前位置: pos0 = %ld\n", pos0);   //0

    //在开始位置写入字符串
    int fail1 = file_puts("//1.你好呀, 11111111!\n", write);
    if (fail1) {
        printf("在开始位置写入字符串失败: fail1 = %d\n", fail1);
    } else {
        printf("在开始位置写入字符串成功!\n");
    }

    //从尾部移动光标
    int fail2 = file_seek(write, -382, SEEK_END);
    printf("1.光标从SEEK_END(末尾位置)偏移 %d 位\n", -382);
    long pos1 = file_tell(write);
    printf("光标当前位置: pos1 = %ld\n", pos1);   //690

    //读一行
    char arr[100] = {0};
    char *str0 = file_gets(arr, 100, write);
    printf("读取1行: \"%s\"\n", arr);
    long pos2 = file_tell(write);
    printf("读一行后, 光标当前位置: pos2 = %ld\n", pos2);   //708

    //读取后, 调用fseek()随便传个值, 否则不能再追加
    file_seek(write, 0, SEEK_CUR);
    long pos3 = file_tell(write);
    printf("读取后, 调用fseek(0)随便传个值, 否则不能再追加. 光标当前位置: pos3 = %ld\n", pos3);//799

    //再在当前位置写入字符串
    int fail3 = file_puts("//2.你好呀, 222222222!\n", write);
    if (fail3) {
        printf("再在当前位置写入字符串失败: fail3 = %d", fail3);
    } else {
        printf("再在当前位置写入字符串成功!\n");
    }
    file_close(write);
}